package main

import (
	"context"
	"errors"
	"fmt"
	"strconv"
)

type WsBalance struct {
	Asset  string `json:"a"`
	Free   string `json:"f"`
	Locked string `json:"l"`
}

type WsOutboundAccountPositionEvent struct {
	EventType  string      `json:"e"`
	EventTime  int64       `json:"E"`
	UpdateTime int64       `json:"u"`
	Balances   []WsBalance `json:"B"`
}

type Balance struct {
	Asset  string
	Free   float64
	Locked float64
}

type Account struct {
	SpotBalances map[string]Balance
}

func (acc *Account) UpdateSpotAccount(asset string, free float64, locked float64) error {
	var balance Balance
	balance.Asset = asset
	balance.Free = free
	balance.Locked = locked
	acc.SpotBalances[asset] = balance
	return nil
}

func NewAccount() *Account {
	pAccount := new(Account)
	pAccount.SpotBalances = make(map[string]Balance)
	return pAccount
}

func (acc *Account) GetAccountSpotBalances() error {
	account, err := binanceClient.NewGetAccountService().Do(context.Background())
	if err != nil {
		Error.Println(err)
		return err
	}
	for _, balance := range account.Balances {
		free, err := strconv.ParseFloat(balance.Free, 64)
		if err != nil {
			Error.Println(err)
			continue
		}
		locked, err := strconv.ParseFloat(balance.Locked, 64)
		if err != nil {
			Error.Println(err)
			continue
		}
		err = acc.UpdateSpotAccount(balance.Asset, free, locked)
		if err != nil {
			Error.Println(err)
		}
	}
	return nil
}

func (acc *Account) GetAssetBalance(asset string) (balance Balance, err error) {
	var bOk bool
	balance, bOk = acc.SpotBalances[asset]
	if bOk {
		err = nil
	} else {
		err = errors.New(fmt.Sprintf("Cannot get balance of %v", asset))
	}
	return
}
